package com.example.bluetoothclicker

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.bluetoothclicker.db.SQLiteHelper

class ConfigFragment : Fragment() {

    private lateinit var dbHelper: SQLiteHelper
    private var isPerspectiveMode = false // 是否为透视模式

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_config, container, false)

        // 初始化 SQLiteHelper
        dbHelper = SQLiteHelper(requireContext())

        // 获取按钮实例
        val forwardButton: Button = rootView.findViewById(R.id.config_forward_button)
        val backwardButton: Button = rootView.findViewById(R.id.config_backward_button)
        val leftButton: Button = rootView.findViewById(R.id.config_left_button)
        val rightButton: Button = rootView.findViewById(R.id.config_right_button)
        val stopButton: Button = rootView.findViewById(R.id.config_stop_button)
        val speedUpButton: Button = rootView.findViewById(R.id.config_speed_up_button)
        val speedDownButton: Button = rootView.findViewById(R.id.config_speed_down_button)

        // 透视模式切换按钮
        val perspectiveButton: Button = rootView.findViewById(R.id.perspective_button)

        // 配置按钮点击事件
        forwardButton.setOnClickListener { handleButtonClick(forwardButton, "前进", "FORWARD") }
        backwardButton.setOnClickListener { handleButtonClick(backwardButton, "后退", "BACKWARD") }
        leftButton.setOnClickListener { handleButtonClick(leftButton, "左转", "LEFT") }
        rightButton.setOnClickListener { handleButtonClick(rightButton, "右转", "RIGHT") }
        stopButton.setOnClickListener { handleButtonClick(stopButton, "停止", "STOP") }
        speedUpButton.setOnClickListener { handleButtonClick(speedUpButton, "加速", "SPEED_UP") }
        speedDownButton.setOnClickListener { handleButtonClick(speedDownButton, "减速", "SPEED_DOWN") }

        // 透视模式切换
        perspectiveButton.setOnClickListener {
            togglePerspectiveMode(
                listOf(
                    forwardButton to "FORWARD",
                    backwardButton to "BACKWARD",
                    leftButton to "LEFT",
                    rightButton to "RIGHT",
                    stopButton to "STOP",
                    speedUpButton to "SPEED_UP",
                    speedDownButton to "SPEED_DOWN"
                )
            )
        }

        return rootView
    }

    /**
     * 处理按钮点击
     * @param button 当前按钮实例
     * @param buttonLabel 按钮的显示名称
     * @param buttonName 按钮标识
     */
    private fun handleButtonClick(button: Button, buttonLabel: String, buttonName: String) {
        if (isPerspectiveMode) {
            // 透视模式下弹出配置窗口
            showInputDialog(button, buttonLabel, buttonName)
        } else {
            // 非透视模式下提示用户
            Toast.makeText(requireContext(), "$buttonLabel 当前配置: ${dbHelper.getCommand(buttonName) ?: "未配置"}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 显示输入框
     */
    private fun showInputDialog(button: Button, buttonLabel: String, buttonName: String) {
        val inputEditText = android.widget.EditText(requireContext())
        inputEditText.hint = "请输入 $buttonLabel 的指令"

        // 从数据库加载现有配置
        val existingCommand = dbHelper.getCommand(buttonName)
        if (existingCommand != null) {
            inputEditText.setText(existingCommand)
        }

        android.app.AlertDialog.Builder(requireContext())
            .setTitle("配置 $buttonLabel 按钮")
            .setView(inputEditText)
            .setPositiveButton("保存") { _, _ ->
                val command = inputEditText.text.toString().trim()
                if (command.isNotEmpty()) {
                    saveCommandToDatabase(button, buttonName, command)
                } else {
                    Toast.makeText(requireContext(), "指令不能为空", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 保存指令到数据库
     */
    private fun saveCommandToDatabase(button: Button, buttonName: String, command: String) {
        val success = dbHelper.insertOrUpdateCommand(buttonName, command)
        if (success) {
            Toast.makeText(requireContext(), "配置已保存", Toast.LENGTH_SHORT).show()
            button.text = command // 更新按钮文本
        } else {
            Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 切换透视模式
     */
    private fun togglePerspectiveMode(buttons: List<Pair<Button, String>>) {
        isPerspectiveMode = !isPerspectiveMode
        for ((button, buttonName) in buttons) {
            if (isPerspectiveMode) {
                // 显示按钮配置内容
                val command = dbHelper.getCommand(buttonName) ?: "未配置"
                button.text = command
            } else {
                // 恢复按钮默认名称
                when (buttonName) {
                    "FORWARD" -> button.text = "前进"
                    "BACKWARD" -> button.text = "后退"
                    "LEFT" -> button.text = "左转"
                    "RIGHT" -> button.text = "右转"
                    "STOP" -> button.text = "停止"
                    "SPEED_UP" -> button.text = "加速"
                    "SPEED_DOWN" -> button.text = "减速"
                }
            }
        }
    }
}
